const {
  $util,
} = getApp();
const MAX_LENGTH = 20;
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    hasMore: true,
    list: [],
    noticeCate: [{ id: 0, title: '公告' }, { id: 1, title: '通知' }],
    noticeid: 0, // 公告分类id 默认为公告
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getList();
    wx.setNavigationBarTitle({
      title: options.barTitle && decodeURIComponent(options.barTitle) || '通知公告',
    });
  },
  getList() {
    let { noticeid } = this.data;
    if (Number(noticeid) === 0) {
      this.getNoticeList();
    } else {
      this.getSysList();
    }
  },
  getNoticeList() {
    let { page } = this.data;
    $util.request({
      url: 'entry/wxapp/system.notice.get_list',
      data: {
        page: page,
      },
      success: (res) => {
        let list = res.data;
        if (page > 1) {
          list = [...this.data.list, ...res.data];
        }
        this.setData({
          list,
          loaded: true,
          hasMore: res.data.length > 0,
          page: res.data.length > 0 ? page + 1 : page,
          isLoad: true,
        });
      },
    });
  },
  // 获取通知列表
  getSysList() {
    let { page } = this.data;
    $util.request({
      url: 'entry/wxapp/system.notice.get_syslist',
      data: {
        page,
      },
      success: (res) => {
        let list = res.data;
        if (page > 1) {
          list = [...this.data.list, ...res.data];
        }
        this.setData({
          list,
          loaded: true,
          hasMore: res.data.length > 0,
          page: res.data.length > 0 ? page + 1 : page,
          isLoad: true,
        });
      },
    });
  },
  changeNav(e) {
    let { id } = e.detail.obj;
    this.setData({
      page: 1,
      noticeid: id,
      list: [],
      isLoad: false,
    }, () => {
      this.getList();
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore) {
      this.getList();
    }
  },
  navigateTo(e) {
    let urlArr = e.currentTarget.dataset.url.split('?');
    let paramArr = {};
    if (urlArr.length > 1) {
      let param = urlArr[1].split('&');
      for (let i = 0; i < param.length; i++) {
        paramArr[param[i].split('=')[0]] = param[i].split('=')[1];
      }
    }
    app.util.navigateTo(urlArr[0], paramArr);
  },
});
